<template>
  <a-modal
    title="添加学生"
    :open="props.modelVisible"
    ok-text="确认"
    cancel-text="取消"
    width="1000px"
    @ok="onOk"
    @cancel="onCancel"
    :maskClosable="true"
    wrap-class-name="full-modal"
    :footer="null"
  >
    <div class="modal-content">
      <a-form ref="formRef" :model="formState" layout="inline" autocomplete="off">
        <div class="filter-content">
          <div class="filter-options">
            <a-row :gutter="[16, 8]">
              <a-col :xs="24" :sm="12" :md="8" :lg="8">
                <a-form-item label="学生名称" name="studentName">
                  <a-input
                    v-model:value="formState.studentName"
                    placeholder="输入学生"
                    allow-clear
                    @change="findAllStudents()"
                  />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="8">
                <a-form-item label="学生ID" name="studentId">
                  <a-input
                    v-model:value="formState.studentId"
                    placeholder="输入ID"
                    allow-clear
                    @change="findAllStudents()"
                  />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="8">
                <a-form-item label="学号" name="studentNo">
                  <a-input
                    v-model:value="formState.studentNo"
                    placeholder="输入学号"
                    allow-clear
                    @change="findAllStudents()"
                  />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="8">
                <a-form-item label="学院" name="college">
                  <a-input
                    v-model:value="formState.college"
                    placeholder="输入学院"
                    allow-clear
                    @change="findAllStudents()"
                  />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="8">
                <a-form-item label="专业" name="major">
                  <a-input
                    v-model:value="formState.major"
                    placeholder="输入专业"
                    allow-clear
                    @change="findAllStudents()"
                  />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="8">
                <a-form-item label="班级" name="className">
                  <a-input
                    v-model:value="formState.className"
                    placeholder="输入班级"
                    allow-clear
                    @change="findAllStudents()"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
          <div class="filter-buttons">
            <a-button type="primary" :disabled="!hasSelected" @click="addStudents()">
              <template #icon><UserAddOutlined /></template>
              添加：{{ state.selectedRowKeys.length }}
            </a-button>
          </div>
        </div>
      </a-form>
      
      <div class="table-container">
        <a-table
          :pagination="false"
          :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :data-source="studentList"
          :loading="tableLoading"
          rowKey="userId"
          :scroll="{ y: '45vh' }"
          size="middle"
        >
          <template #emptyText>
            <span>{{ tableLoading ? '加载中...' : (errorMessage || '暂无数据') }}</span>
          </template>
        </a-table>
        
        <div class="pagination-wrapper">
          <a-pagination
            v-model:current="current"
            v-model:page-size="pageSizeRef"
            :total="total"
            @change="findAllStudents()"
            show-size-changer
            :show-total="(total) => `共 ${total} 条记录`"
          />
        </div>
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import { message, type FormInstance } from 'ant-design-vue';
import { UserAddOutlined } from '@ant-design/icons-vue';
import UserDao from '@/daos/user_dao';
import ClassDao from '@/daos/class_dao';
const userDao = new UserDao();
const classDao = new ClassDao();
//modelVisible用于开关窗口，默认关闭
const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  classId: {
    type: Number
  }
});
//emit用于修改窗口状态
const emit = defineEmits(['update:modelVisible', 'confirm']);
//筛选输入框存储对象
const formState = reactive({
  studentName: '',
  studentId: undefined,
  studentNo: '',
  college: '',
  major: '',
  className: ''
});

//表格数据源
const studentList = ref([]);
//表格加载选项
const tableLoading = ref(false);
//错误信息
const errorMessage = ref('');
//表格列表
const columns = [
  {
    title: '姓名',
    dataIndex: 'studentName',
    align: 'center'
  },
  {
    title: '学号',
    dataIndex: 'studentNo',
    align: 'center'
  },
  {
    title: '学院',
    dataIndex: 'college',
    align: 'center'
  },
  {
    title: '专业',
    dataIndex: 'major',
    align: 'center'
  },
  {
    title: '班级',
    dataIndex: 'className',
    align: 'center'
  }
];
//表格多选存储参数
const state = reactive<{
  selectedRowKeys: [];
}>({
  selectedRowKeys: []
});
const onSelectChange = (selectedRowKeys: []) => {
  state.selectedRowKeys = selectedRowKeys;
};
//计算选中的学生数量是否大于0
const hasSelected = computed(() => state.selectedRowKeys.length > 0);
//分页参数
const current = ref(1);
const pageSizeRef = ref(10);
const total = ref();

//查询所有学生
const findAllStudents = () => {
  // 这里的classId参数用于排除已经在班级中的学生
  // 对于classId，传递值表示获取未在该班级的学生
  if (!props.classId && props.classId !== 0) {
    console.warn('班级ID未提供，无法查询学生');
    errorMessage.value = '班级ID未提供，无法查询学生';
    return;
  }

  tableLoading.value = true;
  errorMessage.value = '';
  
  // 显示查询提示
  const hide = message.loading('正在查询可添加的学生...', 0);
  
  console.log('[前端] 查询学生参数:', {
    classId: props.classId,
    studentId: formState.studentId,
    studentName: formState.studentName,
    currentPage: current.value,
    pageSize: pageSizeRef.value,
    studentNo: formState.studentNo,
    college: formState.college,
    major: formState.major,
    className: formState.className
  });
  
  userDao
    .findAllStudents(
      props.classId,
      formState.studentId,
      formState.studentName,
      current.value,
      pageSizeRef.value,
      formState.studentNo,
      formState.college,
      formState.major,
      formState.className
    )
    .then((result) => {
      hide(); // 关闭加载提示
      
      if (result?.data?.code === 200 && result?.data?.data) {
        console.log('[前端] 学生查询响应数据:', result.data);
        
        const studentRows = result.data.data.rows || [];
        console.log('[前端] 学生数据示例:', studentRows.length > 0 ? JSON.stringify(studentRows[0]) : '无数据');
        
        // 处理返回的数据，支持不同的字段名格式
        studentList.value = studentRows.map(student => ({
          // 必须字段（用于表格展示）
          userId: student.userId,
          studentId: student.studentId || student.student_id,
          studentName: student.studentName || student.student_name || student.userName || student.user_name,
          studentNo: student.studentNo || student.student_no,
          college: student.college,
          major: student.major,
          className: student.className || student.class_name
        }));
        
        total.value = result.data.data.totalCount || 0;
        console.log(`成功加载${studentList.value.length}个学生数据，总共${total.value}条记录`);
        
        if (studentList.value.length === 0) {
          if (total.value === 0) {
            errorMessage.value = '未找到可添加的学生，所有学生可能已在班级中或数据库中没有学生记录';
          } else {
            errorMessage.value = `总共有${total.value}条记录，但当前页无数据`;
          }
          message.info(errorMessage.value);
        }
      } else {
        console.warn('获取学生数据异常:', result);
        studentList.value = [];
        total.value = 0;
        errorMessage.value = result?.data?.msg || '未能获取学生数据';
        message.warning(errorMessage.value);
      }
    })
    .catch((error) => {
      hide(); // 关闭加载提示
      console.error('查询所有学生错误', error);
      studentList.value = [];
      total.value = 0;
      errorMessage.value = '加载学生数据失败，请检查网络连接或后端服务';
      message.error(errorMessage.value);
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

// 添加学生到班级
const addStudents = () => {
  if (!props.classId) {
    message.error('班级ID不存在，无法添加学生');
    return;
  }

  if (state.selectedRowKeys.length === 0) {
    message.warning('请至少选择一名学生');
    return;
  }

  tableLoading.value = true;
  const hide = message.loading('正在添加学生...', 0);
  
  // 获取选中学生的详细信息用于日志
  const selectedStudents = studentList.value.filter(student => 
    state.selectedRowKeys.includes(student.userId)
  );
  
  // 提取用户ID
  const userIds = selectedStudents.map(student => student.userId);
  
  console.log('添加学生详情:', {
    班级ID: props.classId,
    选中学生IDs: userIds,
    学生数量: userIds.length,
    学生详情: selectedStudents.map(s => `${s.studentName}(ID:${s.userId})`)
  });
  
  classDao
    .addClassStudentRef(props.classId, userIds as Array<number>)
    .then((result) => {
      hide(); // 关闭加载提示
      
      if (result?.data?.code === 200) {
        console.log('添加学生成功响应:', result.data);
        message.success(`成功添加${userIds.length}名学生到班级`);
        state.selectedRowKeys = [];
        emit('confirm');
        emit('update:modelVisible', false);
      } else {
        console.error('添加学生失败响应:', result?.data);
        message.error(result?.data?.msg || '添加学生失败');
      }
    })
    .catch((error) => {
      hide(); // 关闭加载提示
      console.error('为项目班添加学生失败:', error);
      message.error('添加学生失败，请检查网络连接');
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

//定义表单
const formRef = ref<FormInstance>();

const onOk = () => {
  formRef.value
    .validateFields()
    .then(() => {})
    .catch((error) => {
      console.error('数据验证失败:', error);
    });
};
const onCancel = () => {
  // formRef.value.resetFields();
  emit('update:modelVisible', false);
};

watch(
  () => props.modelVisible,
  () => {
    if (props.modelVisible == true) {
      // 清空之前的状态
      errorMessage.value = '';
      state.selectedRowKeys = [];
      studentList.value = [];
      
      // 重置分页
      current.value = 1;
      
      // 查询学生
      findAllStudents();
    }
  }
);
</script>

<style scoped>
.modal-content {
  display: flex;
  flex-direction: column;
  height: 70vh;
}

.filter-content {
  display: flex;
  flex-direction: column;
  width: 100%;
  margin-bottom: 16px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
}

.filter-options {
  width: 100%;
}

.filter-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
}
</style>
<style>
.full-modal {
  .ant-modal {
    max-width: 100%;
  }

  .ant-modal-content {
    display: flex;
    flex-direction: column;

    height: calc(75vh);
  }

  .ant-modal-body {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    overflow: auto;
  }
  .ant-modal-footer {
    text-align: end;
    background: transparent;
  }
}
</style>
